package com.example.mypra1.fragments;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.mypra1.R;
import com.example.mypra1.adapter.MyGridAdapter;
import com.example.mypra1.adapter.MyListAdapter;
import com.example.mypra1.adapter.ReplyListAdapter;
import com.example.mypra1.adapter.entity.Comment;
import com.example.mypra1.adapter.entity.Reply;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.szysky.customize.siv.SImageView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 评论详情底部弹框
 */
public  class BottomDialogFragment extends BottomSheetDialogFragment {
    private Context mContext;
    private BottomSheetDialog dialog;
    private int cmtId,rep_count,userId;
    private String profile,pubname,pubtime,content,imgs,edit_content;
    private TextView pubname_tv,content_tv,pubtime_tv,rep_count_tv;
    private SImageView profile_iv;
    private GridView imgs_iv;
    private ImageView edit_submit;
    private EditText edit_reply;
    private ListView listView;
    private List<Reply>replies;
    private Handler handler=new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            Map<String,Object> map = (Map<String, Object>) msg.obj;
            replies = (List<Reply>) map.get("replies");
            rep_count = (int)map.get("count");
            rep_count_tv.setText(map.get("count").toString());
            ReplyListAdapter adapter = new ReplyListAdapter(mContext.getApplicationContext(),R.layout.reply_item,replies);
            listView.setAdapter(adapter);
        }
    };
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (getActivity() == null) return super.onCreateDialog(savedInstanceState);

        dialog = new BottomSheetDialog(getActivity(), R.style.Theme_MaterialComponents_BottomSheetDialog);

        dialog.setContentView(R.layout.view_popup);
        return dialog;

    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        //通过bundle获取从列表项点击详情图标传过来的对应帖子的参数
        cmtId = bundle.getInt("id");//帖子的id
        profile = bundle.getString("profile");//发布者头像
        pubname = bundle.getString("pubname");//发布者昵称
        pubtime = bundle.getString("pubtime");//发布时间
        content = bundle.getString("content");//帖子内容
        imgs = bundle.getString("imgs");//图片
        rep_count = bundle.getInt("rep_count");//回复数量
        //将数据渲染到底部弹框中
        profile_iv = dialog.findViewById(R.id.profile);
        pubname_tv = dialog.findViewById(R.id.pubname);
        pubtime_tv = dialog.findViewById(R.id.pubtime);
        content_tv = dialog.findViewById(R.id.content);
        imgs_iv = dialog.findViewById(R.id.imgs);
        rep_count_tv = dialog.findViewById(R.id.rep_count);
        edit_reply = dialog.findViewById(R.id.edit_reply);
        edit_submit = dialog.findViewById(R.id.edit_submit);
        edit_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 edit_content = edit_reply.getText().toString();
                if(!edit_content.equals("")){
                    SharedPreferences pref = mContext.getSharedPreferences("data",Context.MODE_PRIVATE);
                    userId = pref.getInt("id",3);
                    addData();
                    edit_reply.setText("");
                }
            }
        });
        profile_iv.setImageUrls(profile);
        pubname_tv.setText(pubname);
        pubtime_tv.setText(pubtime);
        content_tv.setText(content);
        String urls[]=imgs.split("&");
        imgs_iv.setAdapter(new MyGridAdapter(urls,getContext()));
        rep_count_tv.setText(String.valueOf(rep_count));
        listView = dialog.findViewById(R.id.list_view);
        getData();
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    /*发送网络请求获取一条帖子对应的回复详情*/
    private void getData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://8.142.19.67:3000/getReply?cmtid="+cmtId)
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            Log.d("resp",response.toString());
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                Log.d("res",res);
                                try {
                                    JSONObject jsonObject = new JSONObject(res);
                                    int count = jsonObject.getInt("count");
                                    JSONArray jsonArray = jsonObject.getJSONArray("results");
                                    Log.d("array",jsonArray.toString());
                                    Map<String,Object>map = new HashMap<>();
                                    map.put("count",count);
                                    List<Reply>reply1 = new ArrayList<>();
                                    for(int i=0;i<jsonArray.length();i++){
                                        JSONObject object = jsonArray.getJSONObject(i);
                                         reply1.add(new Reply(object.getString("profile"), object.getString("username"),
                                                object.getString("content")));
                                    }
                                    map.put("replies",reply1);
                                    Message message = new Message();
                                    message.obj = map;
                                    handler.sendMessage(message);


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else{
                                Log.d("resp",response.toString());
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /*发送post请求，用户发布回复*/
    private void addData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    FormBody.Builder formBody = new FormBody.Builder();
                    //请求体参数帖子主键cmtid,回复者主键pubid,回复内容content
                    formBody.add("pubid",String.valueOf(userId));
                    formBody.add("cmtid",String.valueOf(cmtId));
                    formBody.add("content",edit_content);
                    Request request = new Request.Builder()
                            .url("http://8.142.19.67:3000/addReply")
                            .post(formBody.build())
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            Log.d("resp",response.toString());
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                Log.d("res",res);
                                try {
                                  JSONObject jsonObject = new JSONObject(res);
                                  int code = jsonObject.getInt("code");
                                  if(code==200){
                                      getData();
                                      EventBus.getDefault().post(cmtId);
                                  }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else{
                                Log.d("resp",response.toString());
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
